<?php

namespace app\common\model\shop\goods;

use app\admin\library\Auth;
use app\common\model\shop\Goods;
use think\Model;


class Acct extends Model
{





    // 表名
    protected $name = 'shop_goods_acct';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [];

    function getTitleAttr($value, $data)
    {
        if (!empty($data['goods_id'])) {
            return Goods::where('id', $data['goods_id'])->value('title');
        }
    }

    public function goods()
    {
        return $this->belongsTo('app\common\model\shop\Goods', 'goods_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function pt()
    {
        return $this->belongsTo('app\common\model\Acct', 'acct_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    protected static function init()
    {
        self::afterUpdate(function ($row) {
            $original = $row->origin;
            $change = $row->getChangedData();
            if (isset($change['stock']) && $change['stock'] != $original['stock']) {

                $auth = new Auth();
                $admin_id = $auth->isLogin() ? $auth->id : 0;
                $log = new \app\common\model\shop\Goodsstocklog();
                $log->acct_id = $row->acct_id;
                $log->goods_id = $row->goods_id;
                $log->admin_id = $admin_id;
                $log->before = $original['stock'];
                $log->after = $change['stock'];
                $log->save();
            }
        });
    }
}
